package com.lihua.imgs.upload.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author lihua
 * @date 2024/4/9 15:11
 **/


public class FileUploadUtils {
    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            String fileName = extractFilename(file);

            File desc = getAbsoluteFile(baseDir, fileName);
            file.transferTo(desc);
            return getPathFileName(baseDir, fileName);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        String name = file.getOriginalFilename();
        name = "S" + (new Date()).getTime() + "E" + name;
        return name;
    }

    public static final File getAbsoluteFile(String uploadDir, String fileName) {
        File desc = new File(uploadDir + "/" + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    public static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = System.getProperties().getProperty("user.home").length() + 1;
        String currentDir = uploadDir.substring(dirLastIndex);
        return "/" + currentDir + "/" + fileName;
    }


}